<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
  String basePath = request.getContextPath();
  Object email = request.getSession().getAttribute("email");
%>
<!DOCTYPE HTML>
<html>
<head>
  <title>${shProduct.name}</title>
  <jsp:include page="../common/common-css.jsp"></jsp:include>
  <jsp:include page="../common/common-js.jsp"></jsp:include>

  <link rel="stylesheet" type="text/css" href="<%=basePath%>/plugin/simditor/simditor.css"/>
  <script type="text/javascript" src="<%=basePath%>/plugin/simditor/module.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>/plugin/simditor/hotkeys.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>/plugin/simditor/uploader.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>/plugin/simditor/simditor.min.js"></script>

  <style type="text/css">
    .preDesc {
      width: 120px;
    }

    input, textarea, select {
      color: darkgray;
    }

    td {
      padding: 12px
    }
  </style>

</head>
<body style="padding: 0px;margin: 0px;background-color: #f4f7ed">
<jsp:include page="../../head.jsp"></jsp:include>
<div class="container-fluid" style="padding: 0px">
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="padding: 0px">
    <div class="col-xs-0 col-sm-0 col-md-3 col-lg-4"></div>
    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-4" style="">
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="padding: 10px">
        <h4 style="color: #666666;font-weight: bold">编辑商品</h4>
      </div>
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"
           style="padding: 10px;background-color: #ffffff;" align="center">
        <c:choose>
          <c:when test="${shProduct.url == null || shProduct.url == '/img/product.png'}">
            <img src='<%=basePath%>/img/product.png' alt="商品图片" id="productImg"
                 class="img-responsive">
          </c:when>
          <c:otherwise>
            <img src='${shProduct.url}-750x500' alt="商品图片" id="productImg" class="img-responsive">
          </c:otherwise>
        </c:choose>
        <input type="file" onchange="uploadFile(this);" name="filePath" id="filePath"
               style="display: none">
      </div>
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="padding: 10px;background-color: #ffffff;">
        <table style="width: 100%;border-bottom: 1px solid #ebebeb;">
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc">商品名称</td>
            <td align="right">
              <input type="text" class="text-right" style="width: 100%;border: none" id="name"
                     value="${shProduct.name}"
                     maxlength="15">
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc">商品成本(元)</td>
            <td align="right">
              <input type="text" class="text-right NumDecText"
                     style="width: 100%;border: none" id="originalPrice" placeholder="商品成本"
                     maxlength="8" value="${shProduct.originalPrice}">
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc">商品售价(元)</td>
            <td align="right">
              <input type="text" class="text-right NumDecText"
                     style="width: 100%;border: none" id="price" placeholder="商品售价"
                     maxlength="8" value="${shProduct.price}">
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc">商品库存</td>
            <td align="right">
              <input type="text" class="text-right" style="width: 100%;border: none"
                     onkeyup="this.value=this.value.replace(/\D/g,'')"
                     onafterpaste="this.value=this.value.replace(/\D/g,'')" id="inventory"
                     value="${shProduct.inventory}" maxlength="8">
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc">商品单位</td>
            <td align="right">
              <select id="unit" style="border: none">
                <option value="1">斤</option>
                <option value="2">份</option>
                <option value="3">台</option>
                <option value="4">件</option>
                <option value="5">套</option>
              </select>
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td class="preDesc" style="">商品分类</td>
            <td align="right">
              <select id="productType" style="border: none;"></select>
            </td>
          </tr>
          <tr style="border-bottom: 1px solid #ebebeb;">
            <td colspan="2"style="padding: 0px">
              <textarea placeholder="商品描述" id="remark" rows="20" class="textarea"
                        style="width: 100%;border: none;resize: none;">${shProduct.remark}</textarea>
            </td>
          </tr>
        </table>
        <div class="btn-group" role="group" aria-label="..." style="margin: 20px 0px">
          <button id="save" class="btn btn-info">更&nbsp;新</button>
          <button id="offLine" class="btn btn-default">下&nbsp;架</button>
          <button id="onLine" class="btn btn-default">上&nbsp;架</button>
          <button type="button" class="btn btn-default" onclick="history.go(-1)">取&nbsp;消</button>
        </div>
      </div>
    </div>
  </div>
</div>
</div>
<input type="hidden" class="isHomeImg" value="1">
<jsp:include page="../common/common-html.jsp"></jsp:include>
<jsp:include page="../../foot.jsp"></jsp:include>
<input type="hidden" id="productId" value="${shProduct.id}">
</body>
<script language="JavaScript">
  // - 上架商品
  function onlineProduct() {
    $("#onLine").show();
    $("#offLine").hide();
  }
  // - 下架商品
  function offlineProduct() {
    $("#offLine").show();
    $("#onLine").hide();
  }
  function loadProductType() {
    var productType = '${shProduct.productType}';
    var url = '<%=basePath%>/productType/list';
    var param = {pageNo: 1, pageSize: 100};
    $.post(url, param, function (data, status) {
      var item = '';
      item = '<option value=-1>--</option>';
      $("#productType").append(item);
      for (var i = 0; i < data.length; i++) {
        if (data[i].id == productType) {
          item = '<option value="' + data[i].id + '" selected>' + data[i].name + '</option>';
        } else {
          item = '<option value="' + data[i].id + '">' + data[i].name + '</option>';
        }
        $("#productType").append(item);
      }
    })
  }
  // - 动态加载商品上/下架按钮
  function loadDealProductBt(isSoldOut) {
    if (isSoldOut == 0) {
      offlineProduct();
    } else {
      onlineProduct();
    }
  }
  // - 新增商品
  function save() {
    var name = $.trim($("#name").val());
    var price = $.trim($("#price").val());
    var originalPrice = $.trim($("#originalPrice").val());
    var unit = $.trim($("#unit").val());
    var inventory = $.trim($("#inventory").val());
    var remark = $.trim($("#remark").val());
    var productImg = $("#productImg").attr("src");
    var id = $("#productId").val();
    var productType = $("#productType").val();
    if (name == "") {
      alerErr("输入商品名称!");
      return;
    }
    if (originalPrice == "") {
      alerErr("输入商品成本!");
      return;
    }
    if(!validateNum(originalPrice)){
      alerErr('输入成本价不合法');
      return;
    }
    if (price == "") {
      alerErr("输入商品售价!");
      return;
    }
    if(!validateNum(price)){
      alerErr('输入单价不合法');
      return;
    }
    if (inventory == "") {
      alerErr("输入商品库存!");
      return;
    }
    if (productType == -1) {
      alerErr("选择商品类别!");
      return;
    }
    $.ajaxSetup({
      contentType: 'application/json'
    });
    var param = {
      id: id,
      name: name,
      price: price,
      originalPrice: originalPrice,
      unit: unit,
      remark: remark,
      inventory: inventory,
      productType: productType
    };
    var url = "<%=basePath%>/product/update";
    $.post(url, JSON.stringify(param), function (data, status) {
      if (data.code == 200) {
        var backUrl = '<%=basePath%>/product/info?productId=' + id;
        window.location.href = '<%=basePath%>/success?backUrl=' + backUrl;
      } else {
        aler(data);
      }
    })
  }
  // - 商品下架
  function offLine(productId) {
    updateProductStatus(productId, 1);
  }
  // - 商品上架
  function onLine(productId) {
    updateProductStatus(productId, 0);
  }
  // - 更新商品状态
  function updateProductStatus(productId, productStatus) {
    if (productId == null || productId == '') {
      alerErr('请选择商品');
      return;
    }
    var url = '<%=basePath%>/product/updateProductStatus';
    var param = {productId: productId, productStatus: productStatus};
    $.post(url, param, function (data, status) {
      if (data.code == 200) {
        var backUrl = '<%=basePath%>/product/info?productId=' + productId;
        window.location.href = '<%=basePath%>/success?backUrl=' + backUrl;
      } else {
        aler(data);
      }
    })
  }
  // - 更新商品图片
  function updateProductImg(productImg) {
    var productId = "${shProduct.id}";
    var url = "<%=basePath%>/product/updateimg?productId=" + productId + "&url=" + productImg;
    $.post(url, function (data, status) {
      $("#productImg").attr("src", productImg + "-750x500");
      aler(data);
    })
  }
  // - 上传图片
  function uploadFile(obj) {
    $("#loadModal").modal({
      keyboard: false,
      backdrop: 'static'
    });
    var url = "<%=basePath%>/img/upload";
    var isHomeImage = $(".isHomeImg").val();
    $.ajaxFileUpload({
      url: url,
      fileElementId: "filePath",//file标签的id,
      dateType: "text",
      success: function (data, status) {
        // - ajaxFileUpload这儿必须得转换以下
        data = jQuery.parseJSON(jQuery(data).text());
        if (data.code == 200) {
          var temp = data.data;
          if (isHomeImage == 0) {
            insertImg(temp.downloadUrl + '-750x500');
          }
          if (isHomeImage == 1) {
            updateProductImg(temp.downloadUrl);
          }
        } else {
          alerErr(data.msg);
        }
        $("#loadModal").modal('hide');
      },
      error: function (data, status, e) {
        $("#loadModal").modal('hide');
        $("#filePath").replaceWith($("#upload").clone(true));
        alerErr(e);
      }
    });
  }

  function toInsertImg() {
    var email = '<%=email%>';
    if (!validateEmail(email)) {
      return;
    }
    $(".isHomeImg").val(0);
    $("#filePath").click();
  }

  function parseUnit(unit) {
    $("#unit").val(unit);
  }
  $(function () {
    initStyle();
    $('img').addClass('img-responsive');

    var editor = new Simditor({
      textarea: $('#remark'),
      toolbar: [
        'title',
        'bold',
        'italic',
        'underline',
        'strikethrough',
        'color',
        'ol',
        'ul',
        'code',
        'link',
        'image',
        'hr',
        'indent',
        'outdent',
        'alignment'
      ],
      upload: {
        url: "<%=basePath%>/img/uploadForSimditor",
        params: {
          fileElementId: "filePath",
          dateType: "text"
        },
        fileKey: "filePath",
        leaveConfirm: '正在上传...'
      },
      pasteImage: true
    });
    editor.focus();
    editor.on('valuechanged', function (e, src) {
      $('img').addClass('img-responsive');
    })

    $('img').addClass('img-responsive');
    loadProductType();
    if (!validateEmail('<%=email%>')) {
      return;
    }
    parseUnit('${shProduct.unit}');
    $("#productImg").mousemove(function () {
      $(this).css("cursor", "pointer");
    })
    $("#productImg").mouseout(function () {
      $(this).css("cursor", "default");
    })
    // - 上传图片
    $("#productImg").click(function () {
      $(".isHomeImg").val(1);
      $("#filePath").click();
    })
    // - 更新商品
    $("#save").click(function () {
      $(".btn").blur();
      save();
    })
    // - 上架商品
    $("#onLine").click(function () {
      $(".btn").blur();
      onLine(${shProduct.id});
    })
    // - 下架商品
    $("#offLine").click(function () {
      $(".btn").blur();
      offLine(${shProduct.id});
    })
    loadDealProductBt(${shProduct.deleted});
  })
</script>
</html>
